<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\CheckBuyCartRequest;
use App\Http\Requests\CheckCartRequest;
use App\Http\Requests\OrderAppraiseRequest;
use App\Http\Requests\PayRequest;
use App\Http\Requests\CheckBuyRequest;
use App\Http\Requests\BuyRequest;
use App\Http\Requests\RefundInfoRequest;
use App\Http\Requests\OrderDetailRequest;
use App\Http\Requests\RefundRequest;
use App\Http\Requests\RefundHandleRequest;
use App\Http\Requests\RefundOrderRequest;

use App\Models\Message;
use App\Models\ShopGoods;
use App\Models\ShopGoodsScore;
use App\Models\ShopOrderAddress;
use App\Models\ShopOrderAppraise;
use App\Models\ShopOrderAppraiseTag;
use App\Models\ShopOrderGoods;
use App\Models\ShopOrderLog;
use App\Models\ShopRefundLog;
use App\Models\ShopOrderPayment;
use App\Models\ShopPaymentCode;
use App\Models\ShopSeckillGoods;
use App\Models\ShopRefund;
use App\Models\ShopOrderSplit;
use App\Models\ShopRefundReason;
use App\Models\ShopGroupGoods;
use App\Models\ClientUserAddress;
use App\Models\ShopGoodsStock;
use App\Models\Order;
use App\Models\ShopOrder;
use App\Models\Config;
use App\Libraries\AppPay;
use App\Libraries\KdApi;
use App\Models\ShopStore;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;

class OrderController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
        //检测登录
        if($_POST['_cmd']!='order_refund_handle') {
            $this->check_login();
        }
    }

    //获取店铺ID
    public function getStoreID(BasicRequest $request){
        $order_sn = $request->input('order_sn');
        $store_id = ShopOrder::where('order_sn',$order_sn)->value('store_id');
        return json_success('OK',['store_id'=>$store_id]);
    }
    /*
     *  立即购买
     *  2017/9/23
     */
    public function buy(BuyRequest $request){
        $goods_id = $request->input('goods_id');
        $goods_type = $request->input('goods_type');
        $goods_number = $request->input('goods_number');
        $address_id = $request->input('address_id');
        $remark = $request->input('remark');
        if($goods_type==1){
            $goods_number = 1;
        }
        //订单商品数组
        $goods_list[] = [
            'goods_id'=>$goods_id,
            'goods_type'=>$goods_type,
            'goods_number'=>$goods_number,
        ];
        //订单数组
        $order_info = [
            'order_type'=>$goods_type,
            'address_id'=>$address_id,
            'remark'=>$remark,
            'uid'=>$this->uid
        ];
        $order_model = new Order($order_info,$goods_list);
        $order = $order_model->createOrder();
        return json_success('OK',$order);
    }

    /*
     *  立即购买
     *  状态判断
     *  2017/9/23
     */
    public function buy_status(CheckBuyRequest $request){
        $goods_id = $request->input('goods_id');
        $goods_type = $request->input('goods_type');
        $goods_number = $request->input('goods_number');
        $village_id = $request->input('village_id');

        if($goods_type==1){
            $return=ShopSeckillGoods::checkGoodsStatus($goods_id,$village_id);
        }else if($goods_type==2){
            $return=ShopGroupGoods::checkGoodsStatus($goods_id,$village_id,$goods_number);
        }else {
            //普通商品待完善
            return json_error('暂不支持立即购买');
        }
        //默认地址
        $address = ClientUserAddress::getDefaultAddress($this->uid);
        $order_time = '';
        $return['data']['address'] = $address;
        $return['data']['order_time'] = $order_time;
        $return['data']['order_type'] = $goods_type;
        $return['data']['shipping_amount'] = 0;

        $return['data']['send_time'] = date('m月d日',time()+24*3600).'[周'.mb_substr( "日一二三四五六",date("w",time()+24*3600),1,"utf-8").']'.'00:00-19:00';
        if($return['status']==1){
            return json_success('OK',$return['data']);
        }else{
            return json_error($return['msg']);
        }
    }

    /*
   *  购物车购买
   *  状态判断
   *  2017/9/23
   */
    public function cart_buy_status(CheckCartRequest $request){
        $goods_list = $request->input('goods_list');
        $village_id = $request->input('village_id');

        $return=ShopGoods::checkGoodsStatus($goods_list,$village_id);
        $address = ClientUserAddress::getDefaultAddress($this->uid);

        $order_time = '';
        $return['data']['address'] = $address;
        $return['data']['order_time'] = $order_time;

        if($return['status']==1){
            return json_success('OK',$return['data']);
        }else{
            return json_error($return['msg'],$return['data']);
        }
    }

    public function buy_cart(CheckBuyCartRequest $request){
        $goods_list = $request->input('goods_list');
        $address_id = $request->input('address_id');
        $remark = $request->input('remark');
        $village_id = ClientUserAddress::where('id',$address_id)->value('village_id');
        $goods_result = ShopGoods::checkGoodsStatus($goods_list,$village_id);
        if($goods_result['status']!=1){
            return json_error($goods_result['msg'],$goods_result['data']);
        }
        $goods_list = ShopGoods::getGoodsAttr($goods_list);
        $goods_type = ShopGoods::where('id',$goods_list['0']['goods_id'])->value('goods_type');
        foreach ($goods_list as $key=>$val){
            $goods_list[$key]['goods_type']=$goods_type;
        }
        //订单数组
        $order_info = [
            'order_type'=>$goods_type,
            'address_id'=>$address_id,
            'remark'=>$remark,
            'uid'=>$this->uid
        ];

        $order_model = new Order($order_info,$goods_list);
        $order = $order_model->createOrder();
        return json_success('OK',$order);
    }
    /*
     *  获取支付方式
     *  2017/9/23
     */
    public function getPayment(){
        $payment_code=ShopPaymentCode::where(['status'=>1])->select('id','payment_code','payment_name','payment_images')->get();
        return json_success('OK',$payment_code);
    }
    /*
     *  支付
     *  2017/9/23
     */
    public function pay(PayRequest $request){
        $payment_code = $request->input('payment_code');
        $order_sn = $request->input('order_sn');
        $check_payment=ShopPaymentCode::where(['status'=>1,'payment_code'=>$payment_code])->first();
        if(!$check_payment){
            return json_error('该支付方式暂未开通');
        }
        $order_info=ShopOrder::checkOrderStatus($order_sn);
        if($order_info['status']!=1){
            return json_error('该订单已经支付，如有疑问请联系客服');
        }

        ShopOrderPayment::where(['order_sn'=>$order_sn])
            ->update(['payment_type'=>$check_payment->id,'payment_code'=>$payment_code,'payment_name'=>$check_payment->payment_name]);
        //生成支付订单
        $app = new AppPay();
        $product_name = Config::key('company_name')->value('value') ?? '商品订单';
        $notify_url = url('orderNotify/'.$payment_code);

        $sign = $app->$payment_code($order_sn,$product_name,$order_info->pay_amount,$notify_url);
        return json_success('OK',[$payment_code=>$sign]);
    }
    //服务订单支付
    public function service_pay(PayRequest $request){
        $payment_code = $request->input('payment_code');
        $order_sn = $request->input('order_sn');
        $order_amount = $request->input('order_amount');
        $check_payment=ShopPaymentCode::where(['status'=>1,'payment_code'=>$payment_code])->first();
        if(!$check_payment){
            return json_error('该支付方式暂未开通');
        }
        $order_info=ShopOrder::checkOrderStatus($order_sn);
        if($order_info['status']!=1){
            return json_error('该订单不可支付，如有疑问请联系客服');
        }
        ShopOrder::where(['order_sn'=>$order_sn])->update(['order_amount'=>$order_amount]);
        ShopOrderPayment::where(['order_sn'=>$order_sn])
            ->update(
                [
                    'order_amount'=>$order_amount,
                    'pay_amount'=>$order_amount,
                    'payment_type'=>$check_payment->id,
                    'payment_code'=>$payment_code,
                    'payment_name'=>$check_payment->payment_name
                ]);
        ShopOrderSplit::updateServiceOrder($order_sn,$order_amount);
        //生成支付订单
        $app = new AppPay();
        $product_name = Config::key('company_name')->value('value') ?? '商品订单';
        $notify_url = url('orderNotify/'.$payment_code);

        $sign = $app->$payment_code($order_sn.rand('10000','99999'),$product_name,$order_amount,$notify_url);
        return json_success('OK',[$payment_code=>$sign]);
    }
    /**
     * 购物车判断
     * @param BasicRequest $request
     * @return array
     */
    public function cart_check(CheckCartRequest $request){
        $goods_list = $request->input('goods_list');
        $return=ShopGoods::checkCart($goods_list);

        if($return['status']==1){
            return json_success('OK',$return['data']);
        }else{
            return json_error($return['msg'],$return['data']);
        }
    }


    /*
     *  订单列表
     *  2017/9/23
     */
    public function order_list(BasicRequest $request){
        $status = $request->input('status',0);
		if($status==7){
			//查看退款列表 
			$order_list = $this->refund_list($this->uid);
		}else{

			$order_list=ShopOrder::where('uid','=',$this->uid)->select('order_sn','status','order_type','order_amount','express_amount','created_at','updated_at')
				->where(['is_del'=>0])
                ->whereIn('order_type',['1','2','3'])
				->when($status,function($query) use ($status){
						$query->where(['status'=>$status]);
				})->orderBy('id','desc')->pages()->each(function ($v,$k){
					$v->detail();
				});
		}
        return json_success('OK',$order_list);
    }
    public function service_list(BasicRequest $request){
        $status = $request->input('status',0);

        $order_list=ShopOrder::where('uid','=',$this->uid)->select('order_sn','order_type','status','order_amount','express_amount','created_at','updated_at')
            ->where(['is_del'=>0,'order_type'=>4])
            ->when($status,function($query) use ($status){
                $query->where(['status'=>$status]);
            })->orderBy('id','desc')->pages()->each(function ($v,$k){
                $v->detail();
            });

        return json_success('OK',$order_list);
    }

    private function refund_list($uid){
        $refund_list=ShopRefund::where(['uid'=>$uid,'is_del'=>0])->select('refund_sn','status','refund_amount','order_sn','goods_id','created_at','updated_at')->orderBy('id','desc')->get()->each(function($v,$k){
            $v->detail();
        });
        return $refund_list;
    }

	public function status(BasicRequest $request){
		$status_list = array(
			['id'=>0,'name'=>'全部'],
			['id'=>2,'name'=>'待发货'],
			['id'=>5,'name'=>'已完成'],
			['id'=>7,'name'=>'售后']
        );
		return json_success('OK',$status_list);
	}

    //服务订单状态
	public function service_status(BasicRequest $request){
	    $status_list = array(
	        ['id'=>0,'name'=>'全部'],
            ['id'=>2,'name'=>'待派单'],
            ['id'=>1,'name'=>'待付款'],
            ['id'=>4,'name'=>'待评价']
        );
	    return json_success('OK',$status_list);
    }
    /*
     *  订单详情
     *  2017/9/23
     */
    public function detail(OrderDetailRequest $request){
        $order_sn =$request->input('order_sn');

        $order_detail = ShopOrder::where(['order_sn'=>$order_sn,'uid'=>$this->uid])->select('order_sn','status','order_type','order_amount','express_amount','created_at','store_id')->get()->each(function($v,$k){
            $v->detail();
            $v->address();
        })[0];

        if(!$order_detail){
            return json_error('找不到订单');
        }
        if($order_detail->is_del==1){
            return json_error('该订单已删除');
        }
        return json_sussess_obj('OK',$order_detail);
    }

    /*
     *  删除订单
     *  2017/10/5
     */
    public function del(OrderDetailRequest $request){
        $order_sn =$request->input('order_sn');
        $order_detail = ShopOrder::getOrderDetail($order_sn,$this->uid);
        if(!$order_detail){
            return json_error('找不到订单');
        }
		
        if($order_detail->status!=7 && $order_detail->status!=8 && $order_detail->status!=5){
            return json_error('当前状态下不能删除订单');
        }
        if($order_detail->is_del==1){
            return json_error('该订单已删除');
        }
        $return=DB::transaction(function () use($order_sn) {
            $return = ShopOrder::where(['order_sn'=>$order_sn])->update(['is_del'=>1]);
            //插入日志
            ShopOrderLog::createOrderLog($this->uid,$order_sn,'用户删除了订单',$this->uid);
            return $return;
        });
        return json_success('OK',$return);
    }

    /*
     *  订单物流信息
     *  2017/10/5
     */
    public function express(OrderDetailRequest $request){
        $order_sn =$request->input('order_sn');
        $order_detail = ShopOrder::getOrderDetail($order_sn,$this->uid);
        if(!$order_detail){
            return json_error('找不到订单');
        }
        if($order_detail->status<=2){
            return json_error('订单暂未发货');
        }

        $return = array();
        $return['status'] = $order_detail->status;
        $return['order_sn'] = $order_sn;

        $express = ShopOrderAddress::where(['order_sn'=>$order_sn])->first();

        $return['expresss_name'] = $express->express_name?$express->express_name:'';
        $return['express_code'] = $express->express_code?$express->express_code: '' ;
        $return['express_mobile'] = $express->express_mobile?$express->express_mobile:'';
        $return['company_id'] = $express->express_id?$express->express_id:'';
        $return['express_info'] = array();

        if($express->express_id!=0){
            $kd_api = new KdApi();
            $express_info = $kd_api->getOrderTracesByJson($order_sn,$express->express_company_code,$express->express_code);
            $return['express_info'] = json_decode($express_info,true);
        }else{
            $return['express_info'] = new \stdClass();
        }

        return json_sussess_obj('OK',$return);
    }

    /*
     *  取消订单
     *  2017/10/5
     */
    public function cancel(OrderDetailRequest $request){
        $order_sn =$request->input('order_sn');
        $order_detail = ShopOrder::getOrderDetail($order_sn,$this->uid);
        if(!$order_detail){
            return json_error('找不到订单');
        }
        if($order_detail->order_type!=4) {
            if ($order_detail->status != 1) {
                return json_error('当前状态下不能取消订单');
            }
        }else{
            if ($order_detail->status != 2) {
                return json_error('商家已派单，请与商家协商后取消订单');
            }
        }
        $return=DB::transaction(function () use($order_sn) {
            $return = ShopOrder::where(['order_sn'=>$order_sn])->update(['status'=>7]);
            //插入日志
            ShopOrderLog::createOrderLog($this->uid,$order_sn,'用户取消了订单',$this->uid);
            //回滚库存
            ShopOrder::rbackGoodsStock($order_sn);
            //更新分成表状态
            ShopOrderSplit::where(['order_sn'=>$order_sn])->update(['status'=>3]);

            return $return;
        });
        return json_success('OK',$return);
    }

    /*
     *  确认订单
     *  2017/10/5
     */
    public function confirm(OrderDetailRequest $request){
        $order_sn =$request->input('order_sn');
        $return = ShopOrder::confirmOrder($order_sn,$this->uid);
        return json_success('OK',$return);
    }

    /*
     *  修改订单
     *  2017/9/23
     */
    public function editOrder(OrderDetailRequest $request){
        $order_sn =$request->input('order_sn');
    }

    /*
     *  申请退货页面
     *  2017/9/23
     */
	public function refund_reason(BasicRequest $request){
        $order_sn = $request->input('order_sn');
        $goods_id = $request->input('goods_id');
        if(!$order_sn || !$goods_id){
            return json_error('缺少参数');
        }
        $check=ShopRefund::where(['order_sn'=>$order_sn,'goods_id'=>$goods_id])->first();
        $order = ShopOrder::getOrderDetail($order_sn);
        if($check){
            return json_error('该商品已申请退款，请勿重复申请');
        }
        if(!in_array($order->status,['2','3','4','5'])){
            return json_error('该订单无法退款');
        }
        if(time()>(strtotime($order->updated_at)+7*3600*24)){
            return json_error('订单暂无可退款的类型');
        }

        $reason = ShopRefundReason::where(['status'=>1])->orderBy('id','asc')->select('id','detail')->get();
        $refund_type = collect([]);
        $refund_type[0] = ['id'=>2,'name'=>'退款'];
        $refund_type[1] = ['id'=>3,'name'=>'退货'];
		return json_success('OK',['reason'=>$reason,'refund_type'=>$refund_type]);
	}

    /*
     *  申请退货
     *  2017/9/23
     */
    public function refund(RefundRequest $request){
        $order_sn = $request->input('order_sn');
		$goods_id = $request->input('goods_id');
        $reason_id = $request->input('reason_id');
        $refund_type = $request->input('refund_type');
		$detail = $request->input('detail');
        $order_goods_detail = ShopOrderGoods::where(['order_sn'=>$order_sn,'goods_id'=>$goods_id])->first();
		$reason = ShopRefundReason::where(['status'=>1,'id'=>$reason_id])->value('detail');
        $order = ShopOrder::getOrderDetail($order_sn);
		$refund_sn = ShopOrder::createOrderSN();
		if($reason_id==3) {
            $check = ShopRefund::where(['order_sn' => $order_sn, 'reason_id' => 3])->first();
            if ($check) {
                return json_error('该订单已有运费退款申请，请勿重复申请');
            }
            $refund_amount = $order->express_amount;
            if($refund_amount == 0){
                return json_error('该订单免运费，请选择其它退款理由');
            }
        }else{
            $check = ShopRefund::where(['order_sn' => $order_sn, 'goods_id' => $goods_id])->first();
            if ($check) {
                return json_error('该商品已申请退款，请勿重复申请');
            }
            $refund_amount = bcmul($order_goods_detail->goods_price,$order_goods_detail->goods_number,2);
        }

        if(!in_array($order->status,['3','4','5'])){
            return json_error('该订单已无法退款');
        }
        if(time()>(strtotime($order->updated_at)+15*2600*24)){
            return json_error('订单暂无可退款的类型');
        }

        $return = DB::transaction(function () use($order_sn,$refund_sn,$goods_id,$reason,$detail,$order,$order_goods_detail,$reason_id,$refund_type,$refund_amount) {
            $refund_info = array(
                'order_sn' => $order_sn,
                'refund_sn' => $refund_sn,
                'goods_id' => $goods_id,
                'reason' => $reason,
                'detail' => $detail,
                'order_amount' => $order->order_amount,
                'goods_amount' => bcmul($order_goods_detail->goods_price,$order_goods_detail->goods_number,2),
                'status' => 1,
                'refund_amount' => $refund_amount,
                'reason_id' => $reason_id,
                'refund_type' => $refund_type,
                'uid'=> $this->uid,
                'store_id'=>$order_goods_detail->store_id,
                'created_at'=>date('Y-m-d H:i:s'),
                'updated_at'=>date('Y-m-d H:i:s')
            );

            $return = ShopRefund::insert($refund_info);
            if(!$return){
                throw new \Exception('插入退款表失败');
            }
            $status=ShopOrderGoods::where(['order_sn' => $order_sn, 'goods_id' => $goods_id])->update(['refund_status'=>1]);
            if(!$status){
                throw new \Exception('更新订单状态失败');
            }

            ShopOrder::where(['order_sn'=>$order_sn])->update(['refund_status'=>1]);
            ShopOrderSplit::refund($order_sn);
            $details = '用户申请退款';
            $create=ShopOrderLog::createOrderLog($this->uid,$order_sn,$details,'用户',2);
            if(!$create){
                throw new \Exception('插入订单日志失败');
            }
            $create=ShopRefundLog::createOrderLog($this->uid,$refund_sn,$details,'用户',1);
            if(!$create){
                throw new \Exception('插入退款日志失败');
            }
            //发送消息
            Message::message_push($refund_info['store_id'],'new_refund','您有一条的退款申请待处理，退款单号：'.$refund_sn.'请及时处理',$refund_sn,1);
            return $return;
        });
        if($return){
            return json_success('申请成功',['refund_sn'=>$refund_sn]);
        }else{
            return json_error('系统错误，请重试');
        }
    }

    /*
     *  已付款订单取消退款
     *  2017/9/23
     */
    public function refund_order(BasicRequest $request){
        $order_sn = $request->input('order_sn');
        if(!$order_sn){
            return json_error('参数错误');
        }
        $refund_type = 1;
        $order = ShopOrder::getOrderDetail($order_sn,$this->uid);

        $refund_sn = ShopOrder::createOrderSN();

        $check=ShopRefund::where(['order_sn'=>$order_sn])->first();
        if($check){
            return json_error('该订单已有退款，请勿重复申请');
        }
        if($order->status!=2){
            return json_error('该订单无法取消');
        }

        $refund_info = array(
            'order_sn'=>$order_sn,
            'refund_sn'=>$refund_sn,
            'goods_id'=>'',
            'reason'=>'商品未发货，直接取消',
            'detail'=>'商品未发货，直接取消',
            'refund_reply'=>'商品未发货，直接取消',
            'goods_amount'=>0,
            'status'=>1,
            'store_id'=>$order->store_id,
            'order_amount'=>$order->order_amount,
            'refund_amount'=>$order->order_amount,
            'reason_id'=>0,
            'uid'=>$this->uid,
            'refund_type'=>$refund_type,
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s'),
        );
        $return = DB::transaction(function () use($refund_info) {
            $create = ShopRefund::insert($refund_info);
            if (!$create) {
                throw new \Exception('插入退款表失败');
            }
            $update = ShopOrder::where(['order_sn' => $refund_info['order_sn']])->update(['status' => 7]);
            if (!$update) {
                throw new \Exception('更改订单状态失败');
            }
            //插入申请退款记录
            $details = '用户申请退款';
            $create = ShopOrderLog::createOrderLog($this->uid, $refund_info['order_sn'], $details, $this->uid, 2);
            if (!$create) {
                throw new \Exception('插入订单日志失败');
            }
            $create = ShopRefundLog::createOrderLog($this->uid, $refund_info['refund_sn'], $details, $this->uid, 1);
            if (!$create) {
                throw new \Exception('插入退款日志失败');
            }
            ShopOrderSplit::refundAll($refund_info['order_sn'],$refund_info['refund_amount']);
                        //调用退款接口
            return ShopRefund::AppRefund($refund_info);
        });
        if($return){
            //消息通知
            Message::message_push($refund_info['store_id'],'order_cancel','有一个未发货订单已被用户取消，订单号：'.$refund_info['order_sn'].'，请您注意。',$refund_info['order_sn'],1);
            return json_success('取消成功，请等待资金到账',['refund_sn'=>$refund_sn]);
        }else{
            return json_error('系统错误，请重试');
        }
    }



    /*
     *  退货信息
     *  2017/9/23
     */
    public function refund_info(BasicRequest $request){
        $order_sn = $request->input('order_sn');
        $goods_id = $request->input('goods_id');
        $refund_sn = $request->input('refund_sn');
        if($refund_sn){
            $refund_info = ShopRefund::where(['refund_sn'=>$refund_sn,'is_del'=>0])->select('refund_sn','order_sn','status','refund_amount','reason','detail','refund_type','created_at')->get();
        }else if($order_sn && $goods_id){
            $refund_info = ShopRefund::where(['goods_id'=>$goods_id,'order_sn'=>$order_sn,'is_del'=>0])->select('refund_sn','order_sn','status','refund_amount','reason','detail','refund_type','created_at')->get();
        }else{
            return json_error('参数错误');
        }
        if(!$refund_info->first()){
            return json_error('未找到退款申请');
        }else{

            $refund_info=$refund_info->each(function($v,$k){
                $v->detail();
                $v->other_detail();
            })['0'];
            return json_success('OK',$refund_info);
        }
    }

    /*
     *  申请客服介入与取消退款
     *  2017/9/23
     */
    public function refund_edit(BasicRequest $request){
        $refund_sn = $request->input('refund_sn');
        $status = $request->input('status');
        if(!$refund_sn || !$status){
            return json_error('参数错误');
        }
        $refund_status = ShopRefund::where(['refund_sn'=>$refund_sn])->value('status');
        if($status==1){
            //取消退款
            if(!in_array($refund_status,[1,4])){
                return json_error('当前状态不能取消退款');
            }
            $return = DB::transaction(function () use($refund_sn) {
                $refund_info = ShopRefund::where(['refund_sn'=>$refund_sn])->first();
                $update=ShopRefund::where(['refund_sn'=>$refund_sn])->update(['status'=>6]);

                if(!$update){
                    throw new \Exception('操作失败请重试');
                }
                $details = '用户取消退款';
                $update= ShopRefundLog::createOrderLog($this->uid,$refund_sn,$details,$this->uid,6);
                if(!$update){
                    throw new \Exception('操作失败请重试');
                }
                $update = ShopOrderGoods::where(['order_sn'=>$refund_info->order_sn,'goods_id'=>$refund_info->goods_id])->update(['refund_status'=>3]);
                if(!$update){
                    throw new \Exception('操作失败请重试');
                }
                return true;

            });
        }else if($status==2){
            if($refund_status!='3'){
                return json_error('当前状态不能申请客服介入');
            }
            $return=DB::transaction(function () use($refund_sn) {
                $refund_info = ShopRefund::where(['refund_sn'=>$refund_sn])->first();
                $update=ShopRefund::where(['refund_sn'=>$refund_sn])->update(['status'=>4]);

                if(!$update){
                    throw new \Exception('操作失败请重试');
                }
                $details = '申请客服介入';
                $update=ShopRefundLog::createOrderLog($this->uid,$refund_sn,$details,$this->uid,4);
                if(!$update){
                    throw new \Exception('操作失败请重试');
                }

                $update = ShopOrderGoods::where(['order_sn'=>$refund_info->order_sn,'goods_id'=>$refund_info->goods_id])->update(['refund_status'=>1]);
                if(!$update){
                    throw new \Exception('操作失败请重试');
                }
                $update = ShopOrder::where(['order_sn'=>$refund_info->order_sn])->update(['refund_status'=>1]);
                if(!$update){
                    throw new \Exception('操作失败请重试');
                }
                ShopOrderSplit::refund($refund_info->order_sn);
                return true;
            });
        }
        return json_success('处理完成',$return);
    }

    /*
     *  退款成功接口
     *  @param array $request
    */
	public function refund_handle(RefundHandleRequest $request){
        $status = $request->input('status');
        $refund_sn = $request->input('refund_sn');
        $amount = $request->input('amount');
        $refund_reply = $request->input('detail');
        if($status!=2){
            return json_error('暂不支持其它操作');
        }

        $return=DB::transaction(function () use($refund_sn,$amount,$refund_reply) {
            $refund_status = ShopRefund::where(['refund_sn'=>$refund_sn])->whereIn('status',[1,4])->value('status');
            if(!$refund_status){
                json_error('退款单状态有误或已处理，请重试');
            }
            $update = ShopRefund::where(['refund_sn'=>$refund_sn])->update(['refund_amount'=>$amount,'refund_reply'=>$refund_reply]);
            if(!$update){
                json_error('更新订单状态失败');
            }
            $refund_info = ShopRefund::where(['refund_sn'=>$refund_sn])->first()->toArray();
            ShopOrderSplit::refund_success($refund_info['order_sn'],$amount);
            Message::message_push($refund_info['store_id'],'system_refund_handle','您有一个售后申请已由平台客服处理，退款单号：'.$refund_sn.'，退课金额'.$amount.'，请您注意。',$refund_sn,1);
            Message::message_push($refund_info['uid'],'refund_success','您有一个售后申请已退款，退款单号：'.$refund_sn.'，退课金额'.$amount.'，请您注意。',$refund_sn);

            return ShopRefund::AppRefund($refund_info,'慧生活管理员');
        });
        return json_success('处理完成',$return);
	}

    /*
     * 订单评价
     */
    public function order_appraise(OrderAppraiseRequest $request){
        $insert=array();
        $insert['order_sn'] = $request->input('order_sn');
        $insert['score'] = $request->input('score');
        $insert['detail'] = $request->input('detail');
        $insert['uid'] =$this->uid;

        $return=DB::transaction(function() use($insert){
            $order =ShopOrder::where('order_sn',$insert['order_sn'])->first();
            $insert['store_id'] =$order->store_id;
            if($order['status']!=4){
               throw new \Exception('该订单无法评价');
            }
            ShopOrderAppraise::create($insert);
            ShopOrderGoods::where('order_sn',$insert['order_sn'])->get()->each(function($v,$k) use($insert){
                ShopGoodsScore::create(['store_id'=>$insert['store_id'],'goods_id'=>$v->goods_id,'score'=>$insert['score']]);
            });
            ShopOrder::where('order_sn',$insert['order_sn'])->update(['status'=>5]);
            
            ShopOrderLog::createOrderLog($insert['uid'],$insert['order_sn'],'用户评价了订单,订单号：'.$insert['order_sn'],$insert['uid']);
            return true;
        });
        if($return) {
            $score = ShopOrderAppraise::getSoreNum($insert['store_id']);
            ShopStore::where('id', $insert['store_id'])->update(['score'=>$score]);
            return json_success('OK');
        }else{
            return json_error('评价失败，请稍后再试');
        }
    }

    /*
     * 订单评价标签
     */
    public function appraise_tag(){
        $tag = ShopOrderAppraiseTag::get();
        return json_success('OK',$tag);
    }

    public function service_store_info(BasicRequest $request){
        $this->validate($request,[
            'order_sn' => 'required',
        ],[
            'order_sn.required'=>'缺少id参数',
        ]);
        $order_sn = $request->input('order_sn');
        $store_info=ShopOrder::where(['order_sn'=>$order_sn])->select('store_id','order_amount')->first();
        $return = ShopStore::where(['id'=>$store_info->store_id])->select('id as store_id','store_name','address','store_info','store_logo')->first();
        $return->order_amount = $store_info->order_amount;
        return json_success('OK',$return);
    }
}
